package com.kirk.cts.core.runcycle.schedule.processor.support;

import com.kirk.cts.core.exception.SystemException;
import com.kirk.cts.core.runcycle.schedule.Schedule;
import com.kirk.cts.core.runcycle.schedule.processor.IRunScheduleProcessor;
import org.eclipse.swt.widgets.Display;
import org.springframework.stereotype.Component;

/**
 * <p> DisplayStartThreadProcessor.java </p>
 *
 * @version 1.0.0
 * @Author kirkliu
 * @Date 2020-08-30 16:50
 * @Description SWT display启动线程processor,为了保证swt在p2里面的隔离性，必须保证display的启动线程是单独的线程，和主程序以及app不在一个线程中
 */
@Component
public class DisplayStartThreadProcessor extends AbstractScheduleProcessor implements IRunScheduleProcessor {

    /**
     * display实例
     */
    private static Display display;

    @Override
    public int getIndex() {
        return 3;
    }

    /**
     * 创建display
     */
    private void createDisplay(final Schedule phase) {
        display = Display.getDefault();
        while (true) {
            try {
                if (!display.readAndDispatch()) {
                    display.sleep();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    protected String getThreadName() {
        return "displayThread";
    }

    @Override
    protected boolean isNewThread() {
        return true;
    }

    public static Display getDisplay() {
        if (display == null) {
            throw new SystemException("没有初始化display，请在StartPhase启动DisplayStartThreadProcessor");
        }
        return display;
    }

    @Override
    protected void doExecute(Schedule schedule) {
        createDisplay(schedule);
    }

}
